<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Request;
use Jedrzej\Pimpable\PimpableTrait;

class Category extends Model
{
    use HasFactory, PimpableTrait;

    // 分组 科目分类 考试分类 试卷分类 题库分类 菜单
    const CATEGORY_GROUP = ['subject', 'examination', 'paper', 'text-bank', 'menu'];

    // 可批量赋值的字段
    protected $fillable = ['name', 'flag', 'category_group_id', 'user_id', 'pid', 'status'];

    // 可搜索的字段
    protected $searchable = ['category_group_id', 'status'];

    // 隐藏的字段
    protected $hidden = [
        'user_id',
        'created_at',
        'updated_at',
    ];

    // 设置默认排序字段
    protected $defaultSortCriteria = ['id,desc'];

    // 设置排序关键字
    protected $sortParameterName = 'sortBy';

    /**
     * 和父级分类的关联
     *
     * @return HasMany
     */
    public function children()
    {
        return $this->hasMany(Category::class, 'pid', 'id')
            ->select('id', 'name', 'flag', 'pid', 'status', 'category_group_id', 'user_id')->with('children', function ($query) {
                $query->select('id', 'name', 'flag', 'pid', 'status', 'category_group_id', 'user_id');
            });
    }

    /**
     * 和分组的关联
     *
     * @return BelongsTo
     */
    public function categoryGroup()
    {
        return $this->belongsTo(CategoryGroup::class, 'category_group_id', 'id');
    }

    /**
     * 和用户的关联
     *
     * @return BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}
